﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace Dormsystem
{
    class DB
    {
        private static SqlConnection GetConnection()
        {
            SqlConnection conn = new SqlConnection();

            string src = "Data Source=WAN-PC;Initial Catalog=Dormitory;Integrated Security=True";

            conn.ConnectionString = src;

            conn.Open();

            return conn;
        }

        /// <summary>
        /// 执行sql，完成插入，删除，更改
        /// </summary>
        /// <returns>大于0表示成功</returns>
        public static int ExcuteSQL(string sql)
        {
            SqlConnection cn = GetConnection();
            SqlCommand cmd = new SqlCommand(sql, cn);

            int result = cmd.ExecuteNonQuery();

            cn.Close();

            return result;
        }

        /// <summary>
        /// 执行sql，将结果以DataReader返回
        /// </summary>
        /// <returns></returns>
        public static SqlDataReader GetDataReader(string sql)
        {
            SqlConnection cn = GetConnection();
            SqlCommand cmd = new SqlCommand(sql, cn);

            SqlDataReader dr = cmd.ExecuteReader();

            return dr;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sql"></param>
        /// <returns>返回单个的值</returns>
        public static object GetScalar(string sql)
        {
            SqlConnection cn = GetConnection();
            SqlCommand cmd = new SqlCommand(sql, cn);

            object result = cmd.ExecuteScalar();

            cn.Close();

            return result;
        }

        //返回DataTable对象
        public static DataTable GetDataTable(string sql)
        {
            SqlConnection cn = GetConnection();
            SqlCommand cmd = new SqlCommand(sql, cn);

            SqlDataAdapter adp = new SqlDataAdapter(cmd);

            DataSet ds = new DataSet();

            adp.Fill(ds, "Temp");

            cn.Close();

            return ds.Tables["Temp"];
        }
    }
}
